import stringify from 'fast-json-stable-stringify';

/**
 * 保存数据到浏览器Local Storage
 * @param key   数据key
 * @param data 数据值(只能是Json对象)
 * @param time 过期时间
 */
function setStore(key: string, data: any = '' , time: number): void {   
  const obj = {
    data,
    expire: time
  }
  localStorage.setItem(key, JSON.stringify(obj))
}

/**
 * 从浏览器Local Storage中读取数据
 * @param key       数据key
 */
function getStore<T = any>(key: string, ignoreErr: boolean = true): T | null {
  let data: any = localStorage.getItem(key);

  const time = new Date().getTime();
  if (data) {
    try {
      data = JSON.parse(data);
      if (time < data.expire) 
        data = data.data;
       else    removeStore(key);    
    } catch (err) {
        data = null;
    }
  } else {
    data = null;
  }
  return data
}

/**
 * 从浏览器Local Storage中删除数据
 * @param key 数据key
 */
function removeStore<T = any>(key: string): T | null {
  const value = getStore<T>(key);
  localStorage.removeItem(key);
  return value;
}

/**
 * 清除浏览器Local Storage中的所以数据
 */
function clearStore(): void {
  localStorage.clear();
}
export {
  setStore,
  getStore,
}
